package cn.tradewin.pmp.pages.master;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.BeanModelSource;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;

import cn.tradewin.pmp.persist.model.MPosition;
import cn.tradewin.pmp.services.PositionManageService;

public class PositionManage {
	
	@Property
	private final PositionEncoder positionEncoder = new PositionEncoder();

	@Property
	List<MPosition> positions;

	private MPosition position;
	
	@Property
	private MPosition updPosition;

	@Property
	private MPosition addPosition;

	private boolean inFormSubmission;

	private List<MPosition> positionsSubmitted;

	@Inject
	private PositionManageService positionService;

	@Inject
	private BeanModelSource beanModelSource;
	
	@Property
	private BeanModel<MPosition> beanModel;

	@Inject
	private Messages messages;
	
	@Inject
	private ComponentResources resources;
	
	@Environmental
	private JavaScriptSupport js;
	
	@Inject
	Logger log;
	
	@Log
	void onActivate() {
		inFormSubmission = false;
	}

	@Log
	void setupRender() {
		beanModel = beanModelSource.createDisplayModel(MPosition.class, messages);
		beanModel.add("update", null);
		beanModel.include("selected", "positionNo", "positionName", "positionDesc","update");
		beanModel.get("selected").label("");
		beanModel.get("selected").sortable(false);
		beanModel.get("positionNo").sortable(false);
		beanModel.get("positionName").sortable(false);
		beanModel.get("positionDesc").sortable(false);
		beanModel.get("update").label("");
		beanModel.get("update").sortable(false);
	}

	@Log
	void onPrepareForRender() {
		if (positions == null) {
			positions = positionService.getAllPositions();
		}
	}

	@Log
	void onPrepare() {
		if (addPosition == null) {
			addPosition = new MPosition();
		}
		if (updPosition == null) {
			updPosition = new MPosition();
		}
	}

	@Log
	void afterRender() {
		js.require("jquery");
		js.require("bootstrap");
		JSONObject params = new JSONObject();
		params.put("id", "positionList");
		params.put("url", this.getPageLink());
		js.require("PositionManage").invoke("init").with(params);
	}

	@Log
	void onPrepareForSubmit() {
		inFormSubmission = true;
		positionsSubmitted = new ArrayList<MPosition>();
	}

	/**
	 * delete selected department
	 */
	@Log
	void onSuccessFromListForm() {
		List<Integer> delPositions = new ArrayList<Integer>();
		for (MPosition m : positionsSubmitted) {
			if (m.isSelected()) {
				delPositions.add(m.getPositionNo());
			}
		}
		if (delPositions.size() > 0) {
			positionService.DelPositions(delPositions);
		}
	}
	
	void onSuccessFromUpdForm() {
		try {
			updPosition.setUpdateDatetime(new Date());
			positionService.updPosition(updPosition);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Log
	void onSuccessFromAddForm() {
		try {
			positionService.AddPosition(addPosition);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Log
	JSONObject onUpdatePosition(Integer positionNo) {
		ObjectMapper objectMapper = new ObjectMapper();
		updPosition = positionService.findPositionByPrimary(positionNo);
		if (updPosition != null) {
			try {
				return new JSONObject(objectMapper.writeValueAsString(updPosition));
			} catch (JsonGenerationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	
	private String getPageLink() {
		Link link = resources.createEventLink("updatePosition");
		return link.toAbsoluteURI();
	}
	
	public boolean isNoData() {
		if (positions == null || positions.size() == 0)
			return true;
		return false;
	}
	
	public MPosition getPosition() {
		return position;
	}

	public void setPosition(MPosition position) {
		this.position = position;
		if (inFormSubmission) {
			this.positionsSubmitted.add(position);
		}
	}
	
	private class PositionEncoder implements ValueEncoder<MPosition> {

		public String toClient(MPosition value) {
			return value.getPositionNo().toString();
		}

		public MPosition toValue(String clientValue) {
			MPosition m = new MPosition();
			m.setPositionNo(Integer.parseInt(clientValue));
			return m;
		}
	}	
}
